// https://leetcode.cn/problems/rotate-list/?envType=study-plan-v2&envId=top-interview-150

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if (head == nullptr) {
            return head;
        }

        int n = 1;
        ListNode* cur = head;
        while (cur->next) {
            n++;
            cur = cur->next;
        }
        ListNode* tail = cur;
        k %= n;

        if (k == 0) {
            return head; 
        }

        cur = head;
        for (int i = 0; i < n - k - 1; i++) {
            cur = cur->next;
        }

        tail->next = head;
        head = cur->next;
        cur->next = nullptr;

        return head;
    }
};